<?php

namespace app\common\listener;

use think\Container;
use think\facade\Log;
use think\swoole\Websocket;

class Ping
{
    protected Container $container;

    public function __construct(Container $container)
    {
        // 依赖注入
        $this->container = $container;
    }
    public function handle($event): void
    {
        // 假设 $event->data 是客户端发送的 ping 消息内容
        // 可以在这里记录日志或进行其他处理
        Log::info('Received ping from client: ' . json_encode($event->data));

        // 发送 pong 响应
        $this->sendPong($event);
    }

    private function sendPong($event): void
    {
        // 获取 WebSocket 实例
        $websocket = $this->container->make(Websocket::class);

        // 发送 pong 响应
        $websocket->to($websocket->getSender())->emit('pong', ['message' => 'pong']);
    }
}